package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.dao.CameraDataDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.CameraData;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;

@Service
@Transactional
public class CameraServiceImpl implements ICameraService {

    private final HttpClient client = HttpClient.newHttpClient();
    private static final String CAMERA_SERIAL = "AB9831171";
    private static final String ACCESS_TOKEN = "ra.5re72ai38g4y7gky9ghls5dzb2equqku-491d6ysuja-0bzlevz-5zrd54nns";

    @Autowired
    private CameraDataDao cameraDataDao;

    @Override
    public CameraData captureAndSave(Long deviceId) {
        try {
            // 构建form-urlencoded格式的请求体
            String requestBody = String.format("accessToken=%s&deviceSerial=%s&channelNo=%d&quality=%d",
                    ACCESS_TOKEN,
                    CAMERA_SERIAL,
                    1,
                    2);

            // 发送请求
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://open.ys7.com/api/lapp/device/capture"))
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("Response status: " + response.statusCode());
            System.out.println("Response body: " + response.body());
            
            if (response.statusCode() == 200) {
                JSONObject jsonResponse = new JSONObject(response.body());
                if ("200".equals(jsonResponse.getString("code"))) {
                    String picUrl = jsonResponse.getJSONObject("data").getString("picUrl");
                    
                    // 获取图片数据
                    byte[] imageData = downloadImage(picUrl);
                    
                    // 保存到数据库
                    CameraData cameraData = new CameraData();
                    cameraData.setDeviceId(deviceId);
                    cameraData.setPhoto(imageData);
                    cameraData.setIsDeleted(0);
                    
                    return cameraDataDao.save(cameraData);
                } else {
                    System.err.println("API error: " + jsonResponse.getString("msg"));
                }
            }
            
            System.err.println("Failed to capture image: " + response.body());
            return null;
        } catch (Exception e) {
            System.err.println("Error capturing image: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public CameraData getLatestImage(Long deviceId) {
        List<CameraData> images = cameraDataDao.findLatestByDeviceId(deviceId, PageRequest.of(0, 1));
        return images.isEmpty() ? null : images.get(0);
    }

    private byte[] downloadImage(String imageUrl) {
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(imageUrl))
                    .GET()
                    .build();

            HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
            return response.body();
        } catch (Exception e) {
            System.err.println("Error downloading image: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
} 